package gait.cannon.web.controller;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@SuppressWarnings("unchecked")
@Controller
public class ImageUploadController {

	public final Log log = LogFactory.getLog(getClass());
	
	String[] exts = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
	long maxSize = 10240000;

	@RequestMapping("/imageUpload")
	public void save(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		String path = req.getSession(true).getServletContext().getRealPath("/") + "upload/";
		String url = req.getContextPath() + "/upload/";
		
		resp.setContentType("text/html; charset=UTF-8");
		PrintWriter out = resp.getWriter();

		if (!ServletFileUpload.isMultipartContent(req)) {
			out.println(getError("请选择文件!"));
			return;
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		
		List<FileItem> items =  upload.parseRequest(req);
		for (FileItem item : items) {
			if (item.isFormField())
				continue;
			
			String oldName = item.getName();
			if (item.getSize() > maxSize) {
				out.println(getError("图片文件过大!"));
				return;
			}
			String ext = oldName.substring(oldName.lastIndexOf(".") + 1).toLowerCase();
			if (!Arrays.<String>asList(exts).contains(ext)) {
				out.println(getError("不支持该图片类型上传!"));
				return;
			}
			
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newName = df.format(new Date()) + "_" + oldName;
			
			try {
				File file = new File(path, newName);
				item.write(file);
			} catch (Exception e) {
				out.println(getError("图片上传失败!"));
				return;
			}

			JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", url + newName);
			out.println(obj.toJSONString());
		}
		
	}

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}

}
